/* Copyright (c) 2022-2022, LiWangQian<liwangqian@huawei.com> All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include <catch2/catch.hpp>
#include <iostream>
#include <chrono>
#include "libflexe/infra/event/broker.h"
#include "libflexe/infra/event/basic_event.h"
#include "libflexe/infra/stl/threadpool.h"
#include "libflexe/infra/error.h"

using namespace libflexe::infra;
using namespace std::chrono_literals;

TEST_CASE("test.infra.event.broker.default.event")
{
    event::broker broker{"test-broker"};
    REQUIRE(broker.setup() == OK);
    auto topic_list = broker.list_topics();
    REQUIRE(!topic_list.empty());
    REQUIRE(topic_list.front() == "broker-event");

    bool invoked = false;
    auto ret = broker.sub_from_topic("broker-event", [&](event::ievent &evt) {
        if (evt.type() == event::broker::new_topic_evt) {
            auto &new_topic = dynamic_cast<event::broker::new_topic_event&>(evt);
            REQUIRE(new_topic.topic_name == "system");
            invoked = true;
        }
        return event::event_result::accept;
    });

    REQUIRE(!ret.empty());
    REQUIRE(broker.new_topic("system") == OK);
    REQUIRE(invoked);
}

TEST_CASE("test.infra.event.broker.pub_async.ok")
{
    auto T0 = std::chrono::system_clock::now();
    {
        event::broker broker{"test-broker"};
        REQUIRE(broker.setup() == OK);
        REQUIRE(broker.new_topic("async-topic-1") == OK);
        REQUIRE(broker.new_topic("async-topic-2") == OK);
        std::mutex mtx;
        auto listener = [&](event::ievent &evt) {
            for (auto i = 0; i < 10; ++i) {
                std::this_thread::sleep_for(1ms);
                std::lock_guard<std::mutex> lock{mtx};
                std::cout << std::this_thread::get_id()
                        << ": "
                        << evt.source()
                        << std::endl;

            }
            return event::event_result::accept;
        };

        REQUIRE(!broker.sub_from_topic("async-topic-1", listener).empty());
        REQUIRE(!broker.sub_from_topic("async-topic-2", listener).empty());

        T0 = std::chrono::system_clock::now();
        auto f1 = broker.pub_to_topic_async("async-topic-1",
            stl::make_shared<event::ievent>(0, "caller-1"));
        auto f2 = broker.pub_to_topic_async("async-topic-2",
            stl::make_shared<event::ievent>(0, "caller-2"));
        REQUIRE(f2 == OK);
        REQUIRE(f1 == OK);
    }
    auto T1 = std::chrono::system_clock::now();
    std::cout << "time cost: " << (T1 - T0).count() << std::endl;
}

TEST_CASE("test.infra.event.broker.pub_async.null_event")
{
    event::broker broker{"test-broker"};
    REQUIRE(broker.setup() == OK);
    auto f = broker.pub_to_topic_async("some-topic", nullptr);
    REQUIRE(f == E_NULL_PTR);
}

TEST_CASE("test.infra.event.broker.pub_async.not_topic")
{
    event::broker broker{"test-broker"};
    REQUIRE(broker.setup() == OK);
    auto f = broker.pub_to_topic_async("some-topic",
        stl::make_shared<event::ievent>(0, "test"));
    REQUIRE(f == E_NOT_EXIST);
}

TEST_CASE("test.infra.event.broker.basic_event")
{
    event::broker broker{"test-broker"};
    REQUIRE(broker.setup() == OK);
    broker.new_topic("test/event");

    auto r = broker.sub_from_topic("test/event", [](event::ievent &evt) {
        REQUIRE(evt.type() == 1);
        auto &basic_evt = dynamic_cast<event::basic_event<int>&>(evt);
        basic_evt.value() += 1;
        return event::event_result::accept;
    });
    REQUIRE(!r.empty());

    auto evt = stl::make_shared<event::basic_event<int>>(1, 1, "basic-event");
    REQUIRE(evt != nullptr);
    REQUIRE(broker.pub_to_topic("test/event", evt) == OK);
    REQUIRE(evt->accepted());
    REQUIRE(evt->value() == 2);
}